# coding=utf-8
from pyquery import PyQuery
import time
from export.distributors.b2b import B2b


class Repka(B2b):
    host = 'http://repka.ua/'

    def __init__(self):
        pass

    def handlerHtmlCatalog(self, **kwargs):
        products = []
        self.browser.open(self.host)
        definiteCategoryName = kwargs['definiteCategoryName']
        jQuery = PyQuery(self.browser.response().get_data())
        categories = jQuery('#tabs a')
        for category in categories:
            if category.text:
                categoryName = category.text.encode('utf-8')
                if unicode(categoryName, 'utf-8').lower() == unicode(definiteCategoryName.encode('utf-8'), 'utf-8').lower():
                    products += self.proccessRule(
                        {definiteCategoryName: self.handlerHtmlCategory(url=category.attrib['href'])})
        return products

    def handlerHtmlCategory(self, **kwargs):
        products = []
        url = kwargs['url']
        self.browser.open(url)
        jQuery = PyQuery(self.browser.response().get_data())
        products_ = jQuery('div .title h2 a')
        for product_ in products_:
            product = self.handlerHtmlProduct(url=product_.attrib['href'])
            if product:
                products.append(product)
        lst = jQuery('div .next a')
        time.sleep(2)
        if lst:
            products += self.handlerHtmlCategory(url=lst[0].attrib['href'])
        return products

    def handlerHtmlProduct(self, **kwargs):
        product = {}
        url = kwargs['url']
        self.browser.open(url)
        jQuery = PyQuery(self.browser.response().get_data())
        sku = jQuery('.articul').text()
        if not sku:
            return None
        sku = sku.encode('utf-8').replace('Артикул: ', '')
        if not self.checkProduct(sku, 1):
            return None
        product['sku'] = sku
        product['name'] = jQuery('div .title h1 span[1]').text().replace(' (официальная гарантия)', '')
        product['price'] = self.getProductPriceBySKu(product['sku'])
        product['short_descr'] = jQuery('.desc-text').text().strip()
        product['descr'] = jQuery('.product-description').text().strip()

